package com.cd.common.util;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class EnhancedImageResizer {

    public static void resizeImage(String inputImagePath, String outputImagePath, int targetWidth, int targetHeight, float jpegQuality) throws IOException {
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(new File(inputImagePath));
            if (originalImage == null) {
                throw new IOException("无法加载输入图片：" + inputImagePath);
            }

            // 计算目标尺寸，保持宽高比
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();

            if (targetWidth == -1 && targetHeight == -1) {
                // 如果两个都为-1，则使用原图尺寸
                targetWidth = originalWidth;
                targetHeight = originalHeight;
            } else if (targetWidth == -1) {
                // 根据高度计算宽度，保持宽高比
                double ratio = (double) originalWidth / originalHeight;
                targetWidth = (int) (targetHeight * ratio);
            } else if (targetHeight == -1) {
                // 根据宽度计算高度，保持宽高比
                double ratio = (double) originalHeight / originalWidth;
                targetHeight = (int) (targetWidth * ratio);
            }

            // 创建目标图像
            BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, type);

            // 使用 Graphics2D 进行高质量缩放
            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
            g2d.dispose();

            // 写入输出文件（带压缩质量控制）
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            if (!writers.hasNext()) {
                throw new IllegalStateException("找不到合适的 JPEG 图像写入器！");
            }
            ImageWriter writer = writers.next();
            ImageOutputStream ios = ImageIO.createImageOutputStream(new File(outputImagePath));
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(jpegQuality); // 设置JPEG压缩质量

            writer.write(null, new IIOImage(resizedImage, null, null), param);

            ios.close();
            writer.dispose();

            System.out.println("图片缩放成功！");

        } catch (IOException e) {
            System.err.println("发生错误: " + e.getMessage());
            throw e; // 或者你可以选择在这里进行其他错误处理逻辑
        }
    }

    public static void main(String[] args) {
        try {
            // 调用方法，例如将图片缩小到600x400，并设置JPEG质量为0.85
            resizeImage("input.jpg", "output_600x400.jpg", 600, 400, 0.85f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
